from object_define import PythonMysql
from pymysql import Connection
from datetime import datetime, timedelta
import random

class DatabaseOperations:

    def conn(self):
        conn = Connection(
            host='localhost',
            port=3306,
            user='root',
            password='admin',
            autocommit=True
        )
        conn.select_db('excel')
        return conn



    def insert(self, dataList: list[PythonMysql]):
        print("insert start !!!")
        conn = self.conn()
        cursor = conn.cursor()
        cursor.execute('truncate python_mysql')
        cursor.fetchall()
        for data in dataList:
            str = f'insert into python_mysql (date, count) values(\'{data.date}\', {data.count})'
            print(str)
            cursor.execute(str)
            cursor.fetchall()
        print("insert end !!!")
        conn.close()


if '__main__' == __name__:
    data_list = []
    count = 0
    time = datetime(2024, 1, 1)
    while count < 31:
        str_time = time.strftime("%Y-%m-%d")
        random_int = random.randint(1, 100)
        python_mysql = PythonMysql(str_time, random_int)
        data_list.append(python_mysql)
        count += 1
        time = time + timedelta(days = 1)
    operation = DatabaseOperations()
    operation.insert(data_list)
